function carryOver1 = GenerateCovariates(saveBool, sequenceFiles)
%AdaptID_v1_0: Run the Individual Adaptation experiment
%           AdaptID_v1_0(protocolListFileName)
%
%   AdaptID_v1_0(protocolListFileName) initializes the Individual
%   Adaptation fMRI experiment. This experiment aims to investigate the
%   effect of stimulus history on the current evoked response, when stimuli
%   on serial position -1 to -N are manipulated in a counterbalanced way.
%
%   IMPORTANT!
%   It is recommended that this file is located on ./Experiment/AdaptID_v1_0.m
%   The program will create the ./Data directory for saving the data
%
%
%   Inputs
%   -------
%   [protocolListFileName]: path to a file that should contain a
%           description of the protocols to be used. If nothing is entered,
%           the file ./Config/ProtocolList.cfg will be used
%
%
%   Outputs
%   -------
%   ./Data/[expType]/[protocol]/[subjID]/[subjID]-[protocol]-[iteration].mat
%           this file will store all experimental info, experiment
%           parameters, stimuli used, and data collected
%
%   Examples
%   -------
%    i) AdaptID_v1_0('./protocols.txt')
%   ii) AdaptID_v1_0
%
%   _______________________________________________
%   by Marcelo G Mattar (07/24/2012)
%   mattar@sas.upenn.edu


%% CHECK INPUTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 2
    sequenceFiles = {...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/3targetsA.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/3targetsB.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/4targetsA.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/4targetsB.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/5targetsA.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Experiment/Config/seqs/5targetsB.txt' ...
        };
end

if nargin < 1
    saveBool = 0;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%% PARAMETERS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% General
%expInfo.expType = 'fMRI'; % Experiment type. Enter "fMRI" or "Behavioal" to specify the directory where the data will be saved

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



numFiles = length(sequenceFiles);

% Initialize covariates
carryOver1 = cell(length(sequenceFiles),1);
mainEffect = cell(length(sequenceFiles),1);
afterBlanks = cell(length(sequenceFiles),1);
targetTrials = cell(length(sequenceFiles),1);
afterTargets = cell(length(sequenceFiles),1);


for seqnum = 1:numFiles
    
    % Load the sequence
    thisSeq = double(importdata(sequenceFiles{seqnum}));
    
    mainEffect{seqnum} = ~(thisSeq==0);
    targetTrials{seqnum} = (thisSeq==-1);
    
    % Determine the overlap trials after each blank block
    afterBlanks{seqnum} = findAfterBlankRepeats(thisSeq)';
    
    % Determine the overlap trials after each target trial
    afterTargets{seqnum} = findAfterTargetRepeats(thisSeq)';
    
    carryOver1{seqnum} = ~(targetTrials{seqnum} + ~mainEffect{seqnum} + afterBlanks{seqnum} + afterTargets{seqnum});
end




function overlapTrials = findAfterBlankRepeats(sequence)

    startOfBlankBlocks = [];
    endOfBlankBlocks = [];
    
    if sequence(1) == 0; % If the first element is a blank
        startOfBlankBlocks = 1;
    end
    
    for i=1:(length(sequence)-1)
        if (sequence(i)~=0) && (sequence(i+1)==0)
            startOfBlankBlocks = [startOfBlankBlocks, (i+1)];
        end
        if (sequence(i)==0) && (sequence(i+1)~=0)
            endOfBlankBlocks = [endOfBlankBlocks, i];
        end
    end
    
    if sequence(end) == 0; % If the first element is a blank
        endOfBlankBlocks = [endOfBlankBlocks length(sequence)];
    end
    
    blockAfterBlanks = 1;
    blockBeforeBlanks = 2;
    overlapSize = 20;
    while ~isequal(blockAfterBlanks,blockBeforeBlanks)
        blockAfterBlanks = zeros(length(startOfBlankBlocks),overlapSize);
        blockBeforeBlanks = zeros(length(startOfBlankBlocks),overlapSize);
        
        for blankblock = 1:length(startOfBlankBlocks)
            if startOfBlankBlocks(blankblock) == 1
                if sequence(end) == 0
                    blockBeforeBlanks(blankblock,:) = sequence(((find(sequence~=0, 1, 'last' ))-(overlapSize-1)):(find(sequence~=0, 1, 'last' )));
                else
                    blockBeforeBlanks(blankblock,:) = sequence((end-(overlapSize-1)):end);
                end
            else
                blockBeforeBlanks(blankblock,:) = sequence((startOfBlankBlocks(blankblock)-overlapSize):(startOfBlankBlocks(blankblock)-1));
            end
            
            if endOfBlankBlocks(blankblock) == length(sequence)
                if sequence(1) == 0
                    blockAfterBlanks(blankblock,:) = sequence((find(sequence~=0, 1 )):(find(sequence~=0, 1 )+overlapSize-1));
                else
                    blockAfterBlanks(blankblock,:) = sequence(1:overlapSize);
                end
            else
                blockAfterBlanks(blankblock,:) = sequence((endOfBlankBlocks(blankblock)+1):(endOfBlankBlocks(blankblock)+overlapSize));
            end
        end
        overlapSize = overlapSize - 1;
    end
    
    overlapSize = overlapSize + 1;
    
    % Now that we know the size of the overlap block, find overlap trials
    overlapTrialsIndices = [];
    for blankblock = 1:length(endOfBlankBlocks)
        if endOfBlankBlocks(blankblock) < length(sequence)-overlapSize
            thisBlock = (endOfBlankBlocks(blankblock)+1):(endOfBlankBlocks(blankblock)+overlapSize);
            overlapTrialsIndices = [overlapTrialsIndices thisBlock];
        end
    end
    
    overlapTrials = zeros(1,length(sequence));
    overlapTrials(overlapTrialsIndices) = 1;
    

    
    
    
    
function overlapTrials = findAfterTargetRepeats(sequence)

    targetTrials = find(sequence==-1);
    
    blockBeforeTargets = 2;
    blockAfterTargets = 1;
    overlapSize = 20;
    while ~isequal(blockBeforeTargets,blockAfterTargets)
        blockBeforeTargets = zeros(length(targetTrials),overlapSize);
        blockAfterTargets = zeros(length(targetTrials),overlapSize);
        
        for thisTarget = 1:length(targetTrials)
            blockBeforeTargets(thisTarget,:) = sequence((targetTrials(thisTarget)-overlapSize):(targetTrials(thisTarget)-1));
            blockAfterTargets(thisTarget,:) = sequence((targetTrials(thisTarget)+1):(targetTrials(thisTarget)+overlapSize));
        end
        overlapSize = overlapSize - 1;
    end
    
    overlapSize = overlapSize + 1;
    
    % Now that we know the size of the overlap block, find overlap trials
    overlapTrialsIndices = [];
    for blankblock = 1:length(targetTrials)
        thisBlock = (targetTrials(blankblock)+1):(targetTrials(blankblock)+overlapSize);
        overlapTrialsIndices = [overlapTrialsIndices thisBlock];
    end
    
    overlapTrials = zeros(1,length(sequence));
    overlapTrials(overlapTrialsIndices) = 1;
    
